package cn.intertion.service.impl;

import cn.intertion.dao.OperatorMapper;
import cn.intertion.model.Operator;
import cn.intertion.model.OperatorExten;
import cn.intertion.model.wxObj;
import cn.intertion.service.WXScanners;
import cn.intertion.utils.JSONUtil;
import cn.intertion.utils.URLUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WXScannerImpl implements WXScanners {
    private static final Logger log = LoggerFactory.getLogger(WXScannerImpl.class);
    @Autowired
    private OperatorMapper operatorMapper;

    @Value("${wechatStatus}")
    private String wechatStatus;



    @Override
    public void notifyUsers() throws Exception {
        //有未读消息重复推送
//        List<OperatorExten> li = operatorMapper.getUsersToNotify();
        //有未推送的新消息推送
        List<OperatorExten> li = operatorMapper.getUsersToNotify2(wechatStatus);

        for (OperatorExten oe : li) {
            String openid = oe.getUserOpenId();
            if (openid != null && !openid.equals("")) {
                //通知用户。。。
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("touser", openid);   // openid
                jsonObject.put("template_id", wxObj.moudleId);
                jsonObject.put("url", wxObj.myUrl);
                JSONObject data = new JSONObject();
                JSONObject first = new JSONObject();
                first.put("value", "ShipsCome消息提醒");
                JSONObject keyword1 = new JSONObject();
                keyword1.put("value", "您的ShipsCome上新消息未读，注意查收！");
                JSONObject keyword2 = new JSONObject();
                Calendar now = Calendar.getInstance();
                keyword2.put("value", now.get(Calendar.YEAR) + "年" + (now.get(Calendar.MONTH) + 1) + "月" + now.get(Calendar.DAY_OF_MONTH) + "日"
                +now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+":"+now.get(Calendar.SECOND));
                data.put("first", first);
                data.put("keyword1", keyword1);
                data.put("keyword2", keyword2);
                jsonObject.put("data", data);
                String str = URLUtils.sendPostJsonStr(wxObj.http6 + wxObj.accessToken, jsonObject.toJSONString());
                log.error(str);
                //更新已推送过的消息状态
                operatorMapper.updateNotifyId(oe.getOperatorId(),oe.getMaxlastid());

            }

        }

    }
}
